﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Peppers.Win32;

namespace System.Peppers.UI
{
    /// <summary>
    /// Lightweight version of a GDI+ Bitmap
    /// </summary>
    public sealed class Bitmap : UnmanagedObject
    {
        private const int DEFAULT_TRANPARENT = 0x5f5f5f;

        /// <summary>
        /// Constructor for a stream
        /// </summary>
        /// <param name="stream">Stream of bitmap image</param>
        public Bitmap(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentException();
            }
            IntPtr zero = IntPtr.Zero;
            int status = GdiPlus.GdipCreateBitmapFromStream(new NativeStream(stream), out zero);
            if (status != 0)
            {
                throw GdiPlus.ToGdiException(status);
            }
            status = GdiPlus.GdipImageForceValidation(new HandleRef(null, zero));
            if (status != 0)
            {
                GdiPlus.GdipDisposeImage(new HandleRef(null, zero));
                throw GdiPlus.ToGdiException(status);
            }
            Handle = zero;
        }

        /// <summary>
        /// Creates a Gdi32 bitmap handle
        /// </summary>
        /// <returns>a new HBitmap instance</returns>
        public HBitmap GetHbitmap()
        {
            IntPtr zero = IntPtr.Zero;
            int status = GdiPlus.GdipCreateHBITMAPFromBitmap(new HandleRef(this, Handle), out zero, DEFAULT_TRANPARENT);
            if (status != 0)
            {
                throw GdiPlus.ToGdiException(status);
            }
            return zero;
        }

        /// <summary>
        /// Calls GdiPlus.GdipDisposeImage
        /// </summary>
        public override void Dispose()
        {
            base.Dispose();

            if (Handle != IntPtr.Zero)
            {
                int status = GdiPlus.GdipDisposeImage(new HandleRef(null, Handle));
                if (status != 0)
                {
                    throw GdiPlus.ToGdiException(status);
                }
                Handle = IntPtr.Zero;
            }
        }
    }
}
